# SPDX-License-Identifier: BSD-2-Clause

import os

from migen import *
from litex.gen import *
from litex.soc.interconnect import wishbone

# AES128 Wishbone -----------------------------------------------------------------------------------------

class AES128(LiteXModule):
    def __init__(self, platform):

        self.wb_ctrl = wb_ctrl = wishbone.Interface(data_width=32, address_width=32, addressing="word")

        self.interrupt = Signal()

        # # #

        # AES128 Wishbone Core Instance.
        self.specials += Instance(self.get_netlist_name(),
            # Clk / Rst.
            i_clk   = ClockSignal("sys"),
            i_reset = ResetSignal("sys"),
            # Wishbone Control.
            i_wb_cyc_i    = wb_ctrl.cyc,
            i_wb_stb_i    = wb_ctrl.stb,
            o_wb_ack_o    = wb_ctrl.ack,
            i_wb_we_i     = wb_ctrl.we,
            i_wb_adr_i    = wb_ctrl.adr,
            o_wb_dat_o    = wb_ctrl.dat_r,
            i_wb_dat_i    = wb_ctrl.dat_w,
            i_wb_sel_i    = wb_ctrl.sel,
            # Interrupt.
            o_wb_int_o = self.interrupt,
        )

        self.add_sources(platform)

    def get_netlist_name(self):
        return "top_wb_aes_merge" 

    def add_sources(self, platform):

        cdir = os.path.abspath('.')
        vdir = os.path.join(cdir, "AES128_192", "sim")
        netlist_name = self.get_netlist_name()

        print(f"AES128 netlist : {netlist_name}")
        if not os.path.exists(os.path.join(vdir, netlist_name + ".v")):
            self.generate_netlist()

        platform.add_source(os.path.join(vdir,  netlist_name + ".v"), "verilog")

    def generate_netlist(self):
        print(f"Generating AES128 netlist")
        sources = []
        sdir = "AES128_192"
        if not os.path.exists(sdir):
            os.system(f"git clone https://gitee.com/weihemin/aes128_192.git AES128_192")

        cdir = os.path.abspath('.')

        cmd = 'cd {path} && bash merge_rtl_aes128.cmd'.format(
            path=os.path.join(cdir, "AES128_192", "sim") )
        print("!!! "   + cmd)
        if os.system(cmd) != 0:
            raise OSError('Failed to run merge_rtl_aes128')

